package priv.mill.logdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class SocketDemo {
	private static Map<String,Servlet> maps=new HashMap<>();
	static {
		maps.put("/aaa",new YueFei());
		maps.put("/bbb",new qinkuai());
	}
	private static final Logger logger = Logger.getLogger(SocketDemo.class);
	public static void main(String[] args) {
		try {
			ServerSocket socket=new ServerSocket(9000);
			while(true) {
				Socket accept = socket.accept();
				new Thread(()->{
					try {
						handler(accept);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}).start();
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @param accept
	 * @throws IOException
	 */
	public static void handler(Socket accept) throws IOException {
		InputStream inputStream = accept.getInputStream();
		/*int available = inputStream.available();
		int amount=0;*/
		int len;
		byte[] b=new byte[4096];
		StringBuffer stringBuffer = new StringBuffer();
		while((len=inputStream.read(b))!=-1) {
			String x=new String(b,0,len);
			stringBuffer.append(x);
			if(x.contains("\r\n\r\n")) {
				break;
			}
		}
		accept.shutdownInput();
		String[] split=stringBuffer.toString().split("\r\n");
		String path=split[0].split("\\s")[1];
		
		OutputStream outputStream = accept.getOutputStream();
		outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
		/*outputStream.write("<h1>this is my info</h1>".getBytes());*/
		maps.get(path).doGet(outputStream);
		System.out.println("over");
		accept.shutdownOutput();
		accept.close();
	}
}

